package com.github.ilioili.justdoit.widget;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.Scroller;

import java.lang.reflect.Field;

/**
 * Created by hantuo on 16/5/31.
 */
public class PlayViewPager extends ViewPager {

    private Runnable action = new Runnable() {
        @Override
        public void run() {
            if (getCurrentItem() != getAdapter().getCount() - 1 && getVisibility() != View.GONE) {
                setCurrentItem(getCurrentItem() + 1);
                postDelayed(this, 3500);
            } else {
                onEndListener.onEnd();
            }
        }
    };

    public PlayViewPager(Context context) {
        super(context);
        replaceScroller(context);

    }

    private void replaceScroller(final Context context) {
        try {
            Field f = ViewPager.class.getDeclaredField("mScroller");
            f.setAccessible(true);
            f.set(this, new Scroller(context, new DecelerateInterpolator()) {
                @Override
                public void startScroll(int startX, int startY, int dx, int dy, int duration) {
                    super.startScroll(startX, startY, dx, dy, duration * 8);
                }
            });
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        setFocusableInTouchMode(true);
        setFocusable(true);
    }

    public PlayViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        replaceScroller(context);
    }


    public void play(final OnEndListener onEndListener) {
        this.onEndListener = onEndListener;
        postDelayed(action, 3000);
    }

    public void cancel() {
        removeCallbacks(action);
    }

    private OnEndListener onEndListener;


    public interface OnEndListener {
        void onEnd();
    }
}
